#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
角色管理界面
提供角色创建、选择、删除等功能
"""

import os
from typing import List
from ..game.game_manager import GameManager
from ..character.character import Character

class CharacterUI:
    """
    角色管理界面类
    """
    
    def __init__(self, game_manager: GameManager):
        """
        初始化角色管理界面
        
        Args:
            game_manager: 游戏管理器
        """
        self.game_manager = game_manager
    
    def clear_screen(self):
        """
        清屏
        """
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def show_header(self):
        """
        显示标题
        """
        print("\n" + "=" * 50)
        print("                角色管理")
        print("=" * 50)
    
    def show_character_list(self):
        """
        显示角色列表
        """
        characters = self.game_manager.get_all_characters()
        current_character = self.game_manager.get_current_character()
        
        if not characters:
            print("\n暂无角色，请先创建角色。")
            return
        
        print("\n角色列表:")
        print("-" * 80)
        print(f"{'序号':<4} {'角色名':<12} {'职业':<8} {'等级':<6} {'经验':<12} {'状态':<10} {'当前'}")
        print("-" * 80)
        
        for i, character in enumerate(characters, 1):
            # 状态显示
            if character.is_idle:
                status = f"挂机({character.idle_location})"
            elif character.is_in_battle:
                status = "战斗中"
            else:
                status = "空闲"
            
            # 是否为当前角色
            is_current = "★" if current_character and current_character.id == character.id else ""
            
            print(f"{i:<4} {character.name:<12} {character.character_class:<8} "
                  f"{character.level:<6} {character.exp}/{character.exp_to_next_level:<12} "
                  f"{status:<10} {is_current}")
        
        print("-" * 80)
    
    def create_character(self):
        """
        创建新角色
        """
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           创建新角色")
        print("=" * 40)
        
        # 输入角色名
        while True:
            name = input("\n请输入角色名 (3-12个字符): ").strip()
            
            if not name:
                print("角色名不能为空!")
                continue
            
            if len(name) < 3 or len(name) > 12:
                print("角色名长度必须在3-12个字符之间!")
                continue
            
            break
        
        # 选择职业
        classes = self.game_manager.character_manager.get_character_classes()
        
        print("\n可选职业:")
        for i, class_name in enumerate(classes, 1):
            print(f"{i}. {class_name}")
        
        while True:
            try:
                choice = input(f"\n请选择职业 (1-{len(classes)}): ").strip()
                choice_idx = int(choice) - 1
                
                if 0 <= choice_idx < len(classes):
                    character_class = classes[choice_idx]
                    break
                else:
                    print("无效选择，请重新输入!")
            except ValueError:
                print("请输入数字!")
        
        # 创建角色
        success, message, character = self.game_manager.create_character(name, character_class)
        
        print(f"\n{message}")
        
        if success and character:
            print(f"\n角色属性:")
            print(f"  名称: {character.name}")
            print(f"  职业: {character.character_class}")
            print(f"  等级: {character.level}")
            print(f"  生命值: {character.hp}/{character.max_hp}")
            print(f"  魔法值: {character.mp}/{character.max_mp}")
            print(f"  攻击力: {character.attack}")
            print(f"  防御力: {character.defense}")
            print(f"  速度: {character.speed}")
            
            # 询问是否设为当前角色
            while True:
                set_current = input("\n是否设为当前角色？(y/n): ").strip().lower()
                if set_current in ['y', 'yes', '是']:
                    self.game_manager.select_character(character.id)
                    print(f"已设置 {character.name} 为当前角色")
                    break
                elif set_current in ['n', 'no', '否']:
                    break
                else:
                    print("请输入 y 或 n")
        
        input("\n按回车键继续...")
    
    def select_character(self):
        """
        选择角色
        """
        characters = self.game_manager.get_all_characters()
        
        if not characters:
            print("\n暂无角色，请先创建角色。")
            input("按回车键继续...")
            return
        
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           选择角色")
        print("=" * 40)
        
        self.show_character_list()
        
        while True:
            try:
                choice = input(f"\n请选择角色 (1-{len(characters)}) 或输入 0 返回: ").strip()
                
                if choice == "0":
                    return
                
                choice_idx = int(choice) - 1
                
                if 0 <= choice_idx < len(characters):
                    character = characters[choice_idx]
                    success, message = self.game_manager.select_character(character.id)
                    print(f"\n{message}")
                    
                    if success:
                        print(f"\n角色详情:")
                        print(f"  名称: {character.name}")
                        print(f"  职业: {character.character_class}")
                        print(f"  等级: {character.level}")
                        print(f"  经验: {character.exp}/{character.exp_to_next_level}")
                        print(f"  生命值: {character.hp}/{character.max_hp}")
                        print(f"  魔法值: {character.mp}/{character.max_mp}")
                        print(f"  攻击力: {character.attack}")
                        print(f"  防御力: {character.defense}")
                        print(f"  速度: {character.speed}")
                    
                    input("\n按回车键继续...")
                    return
                else:
                    print("无效选择，请重新输入!")
            except ValueError:
                print("请输入数字!")
    
    def delete_character(self):
        """
        删除角色
        """
        characters = self.game_manager.get_all_characters()
        
        if not characters:
            print("\n暂无角色可删除。")
            input("按回车键继续...")
            return
        
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           删除角色")
        print("=" * 40)
        
        self.show_character_list()
        
        while True:
            try:
                choice = input(f"\n请选择要删除的角色 (1-{len(characters)}) 或输入 0 返回: ").strip()
                
                if choice == "0":
                    return
                
                choice_idx = int(choice) - 1
                
                if 0 <= choice_idx < len(characters):
                    character = characters[choice_idx]
                    
                    # 确认删除
                    print(f"\n确定要删除角色 '{character.name}' 吗？")
                    print("警告: 此操作不可恢复!")
                    
                    confirm = input("请输入 'DELETE' 确认删除，或按回车取消: ").strip()
                    
                    if confirm == "DELETE":
                        success, message = self.game_manager.character_manager.delete_character(character.id)
                        print(f"\n{message}")
                    else:
                        print("\n已取消删除操作")
                    
                    input("\n按回车键继续...")
                    return
                else:
                    print("无效选择，请重新输入!")
            except ValueError:
                print("请输入数字!")
    
    def show_menu_options(self):
        """
        显示菜单选项
        """
        print("\n请选择操作:")
        print("1. 创建角色")
        print("2. 选择角色")
        print("3. 删除角色")
        print("0. 返回主菜单")
        print("-" * 30)
    
    def handle_menu_choice(self, choice: str) -> bool:
        """
        处理菜单选择
        
        Args:
            choice: 用户选择
            
        Returns:
            是否继续显示角色管理界面
        """
        if choice == "1":
            self.create_character()
        elif choice == "2":
            self.select_character()
        elif choice == "3":
            self.delete_character()
        elif choice == "0":
            return False
        else:
            print("\n无效选择，请重新输入!")
            input("按回车键继续...")
        
        return True
    
    def show(self):
        """
        显示角色管理界面
        """
        running = True
        
        while running:
            self.clear_screen()
            self.show_header()
            self.show_character_list()
            self.show_menu_options()
            
            try:
                choice = input("请输入选择 (0-3): ").strip()
                running = self.handle_menu_choice(choice)
            except KeyboardInterrupt:
                print("\n\n返回主菜单...")
                break
            except Exception as e:
                print(f"\n发生错误: {e}")
                input("按回车键继续...")